﻿using Easy.Common.Extension;
using Easy.Common.Helper;
using Microsoft.Extensions.Configuration;

namespace Easy.Common.Config
{
    /// <summary>
    /// AppSettings
    /// </summary>
    public partial class AppSettings
    {
        /// <summary>
        /// get enable
        /// </summary>
        /// <returns></returns>
        public static bool GetEnable(string dbConn, string dbName)
        {
            IConfigurationSection section = GetConfigurationSection(dbConn);
            string enable = section.GetSection(dbName)["Enable"];
            return enable.ToBoolean();
        }

        /// <summary>
        /// get connection
        /// </summary>
        /// <param name="dbConn">dbConn</param>
        /// <param name="dbName">dbName</param>
        /// <param name="conntectionName">conntectionName</param>
        /// <returns>return connection</returns>
        public static string GetConnection(string dbConn, string dbName, string conntectionName)
        {
            IConfigurationSection section = GetConfigurationSection(dbConn);
            string connection = section.GetSection(dbName)[conntectionName];
            bool isEncrypt = section.GetSection(dbName)["IsEncrypt"].ToBoolean();
            if (isEncrypt)
            {
                return RSAHelper.Decrypt(connection);
            }
            return connection;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sectionName"></param>
        /// <returns></returns>
        public static IConfigurationSection GetConfigurationSection(string sectionName)
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            //var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true).AddEnvironmentVariables();
            return builder.Build().GetSection(sectionName);
        }

        public static IConfiguration GetConfiguration()
        {
            //return new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true).AddEnvironmentVariables().Build();
            return new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
        }
    }
}
